# cd /projects/data_commons/cw_code/
# bash zb_r.sh "2" "6" "cw_geo_zip_import.R" "" ""

sys_args <- commandArgs(trailingOnly=T)
sys_batch <- ifelse(interactive(),0,1)
print(paste0("Last Modified: ",file.mtime(paste0(Sys.getenv("qpath"),"/",Sys.getenv("qscript")))))

print(sys_args)

dir_proj <- "/projects/data_commons/cw/"
dir_dcw <- dir_proj
setwd(dir_proj)

library(data.table)

print(paste0("Started at ", Sys.time()))
print(sessionInfo())

#===============================================================================

dt_zip <- readRDS(paste0(dir_dcw,"cw_geo_zip_fips_hud_raw.rds"))
# For now, just use 2010Q1 as correct zip codes.
dt_out <- dt_zip[year==2020 & qtr == 1]
dt_out[, c("year","qtr"):=NULL]
dt_out[, fips:=as.integer(fips)]
dt_out[, zipfips:=1]

saveRDS(dt_out,paste0(dir_dcw,"cw_geo_zip_fips.rds"))
haven::write_dta(dt_out,paste0(dir_dcw,"cw_geo_zip_fips.dta"))
fwrite(dt_out,paste0(dir_dcw,"cw_geo_zip_fips.csv"),quote=T)

print(paste0("Ended at ", Sys.time()))
# End of R Script